<?php
namespace frontend\modules\Oauth\extras;

use Yii;
use frontend\modules\Oauth\base\AbstractOauth;
use yii\helpers\ArrayHelper;
use yii\base\Exception;

/**
 * Class WxOauth
 * @package frontend\modules\Oauth\extras
 * 微信授权类
 */
class WxOauth extends AbstractOauth
{

    /**
     * @param array $config
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function getOauth2AuthorizeUrl($config)
    {
        $wechat = self::getWeChat(ArrayHelper::getValue($config,'app_id'),ArrayHelper::getValue($config,'app_secret'));
        // 发起oauth2.0请求
        $state          = 'authorize';
        $inputScope     = ArrayHelper::getValue($config,'scope',2);
        $scope          = $inputScope == 1 ? 'snsapi_base' : 'snsapi_userinfo';
        $oauthUrl       = $wechat->getOauth2AuthorizeUrl($config['callBackUrl'],$state,$scope); //微信后台配置域名不带http
        return $oauthUrl;
    }

    /**
     * @param array $params
     * @throws Exception
     * @return mixed
     */
    public function oauthCallBack($params)
    {
        $wechat = self::getWeChat(ArrayHelper::getValue($params,'app_id'),ArrayHelper::getValue($params,'app_secret'));
        $code       = ArrayHelper::getValue($params,'code');
        $inputScope = ArrayHelper::getValue($params,'scope',2);
        if(!$code){
            throw new Exception('code标识不能为空');
        }
        $result = $wechat->getOauth2AccessToken($code);
        if(!ArrayHelper::getValue($result,'access_token')){
            throw new Exception('获取access_token失败');
        }
        // user_info模式获取用户详情
        if($inputScope == 2){
            $member = $wechat->getSnsMemberInfo($result['openid'],$result['access_token']);
        }else{
            $member = ['openid'=>$result['openid']];
        }
        // 生成hash值 返回键值对
        return [
            'cacheKey' => md5($result['openid']),
            'cacheData' => $member ,
        ];
    }

    /**
     * @param $appId
     * @param $appSecret
     * @return object
     * @throws \yii\base\InvalidConfigException
     */
    protected static function getWeChat($appId,$appSecret)
    {
        $wechat = Yii::createObject([
            'class'     => 'common\components\wechat\Wechat',
            'appId'     => $appId,
            'appSecret' => $appSecret,
            'token'     => '',
        ]);
        /** @var $obj \common\components\wechat\Wechat*/
        return $wechat ;
    }
}